package com.haoshui.job;


import com.haoshui.constants.RedisCacheConstans;
import com.haoshui.domain.entity.Article;
import com.haoshui.service.ArticleService;
import com.haoshui.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class updateViewCount {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    /**
     * 将redis中的viewCount添加到数据库
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void updateViewCount(){
        //获取redis中的viewCount
        Map<String, Integer> countMap = redisCache.getCacheMap(RedisCacheConstans.VIEW_COUNT_KEY_IN_REDIS);

        //转化成ArticleList
        List<Article> articles = countMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());
        //将viewCount存入数据库 todo
        articleService.updateViewCountToDateBase(articles);

    }
}
